package com.elvish.oda.busin.dao;

import java.util.List;

import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.elvish.oda.busin.pojo.Permission;
import com.elvish.oda.busin.pojo.User;
import com.elvish.oda.common.pojo.Page;
import com.elvish.oda.common.utils.CommonUtil;
import com.elvish.oda.common.utils.NutzSqlUtil;

@Component
public class UserDao {

	@Autowired
	Dao dao;

	public User findByUsername(String username) {
		String querySql = "select * from t_user where username = @username";
		Sql sql = Sqls.fetchString(querySql);
		sql.setParam("username", username);
		return NutzSqlUtil.getEntity(sql, dao, User.class);
	}

	public List<Permission> findMyPermitions(User user) {
		String querySql = "select p.permission_code ,ur.role_id roleId from t_permission p left join t_role_permission rp on p.id = rp.permission_id left join t_user_role ur on rp.role_id = ur.role_id where ur.user_id = @userId";
		Sql sql = Sqls.fetchString(querySql);
		sql.setParam("userId", user.getId());
		return NutzSqlUtil.getEntities(sql, dao, Permission.class);
	}

	public int updateUserSelective(User user, String pattern) {
		return dao.update(user, pattern);
	}

	public List<User> findAll() {
		return NutzSqlUtil.getEntities(dao, User.class);
	}

	public List<User> findAllUserRole(Page page) {
		String querySql = "SELECT t1.*, t2.role_name as roleName FROM t_user_role t0 LEFT JOIN t_user t1 ON t0.user_id = t1.id LEFT JOIN t_role t2 ON t0.role_id = t2.id";
		querySql = CommonUtil.limit(querySql, page);
		Sql sql = Sqls.fetchString(querySql);
		return NutzSqlUtil.getEntities(sql, dao, User.class);
	}

	public Integer count() {
		String querySql = "select count(0) from t_user";
		Sql sql = Sqls.fetchString(querySql);
		dao.execute(sql);
		return Integer.parseInt(sql.getString());
	}

}
